<template>
  <div class="draggable-table">
    <h3>可拖拽排序表格</h3>
    <table class="data-table">
      <thead>
      <tr>
        <th>ID</th>
        <th>名称</th>
        <th>数量</th>
        <th>状态</th>
      </tr>
      </thead>
      <tbody ref="tableBody">
      <tr
          v-for="(item, index) in tableData"
          :key="item.id"
          :class="{ 'dragging': isDragging && draggingIndex === index }"
      >
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.quantity }}</td>
        <td>
            <span :class="`status-badge ${item.status}`">
              {{ item.status === 'active' ? '活跃' : '禁用' }}
            </span>
        </td>
      </tr>
      </tbody>
    </table>

    <div class="controls">
      <button @click="resetTable" class="reset-btn">重置排序</button>
      <div class="debug-info" v-if="showDebug">
        <p>当前顺序: {{ tableData.map(item => item.id).join(', ') }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import Sortable from 'sortablejs';

// 表格数据
const tableData = ref([
  { id: 1, name: '产品A', quantity: 25, status: 'active' },
  { id: 2, name: '产品B', quantity: 18, status: 'active' },
  { id: 3, name: '产品C', quantity: 42, status: 'inactive' },
  { id: 4, name: '产品D', quantity: 15, status: 'active' },
  { id: 5, name: '产品E', quantity: 30, status: 'inactive' },
]);

// 原始数据备份，用于重置
const originalData = [...tableData.value];

// 表格体引用
const tableBody = ref(null);

// 拖拽状态
const dragState = reactive({
  instance: null,
  isDragging: false,
  draggingIndex: -1
});

// 控制是否显示调试信息
const showDebug = ref(true);

// 初始化拖拽功能
onMounted(() => {
  if (tableBody.value) {
    // 创建Sortable实例
    dragState.instance = new Sortable(tableBody.value, {
      animation: 150,          // 拖拽动画时长
      ghostClass: 'sortable-ghost', // 拖拽时的占位元素类名
      chosenClass: 'sortable-chosen', // 选中元素的类名
      dragClass: 'sortable-drag',   // 拖拽元素的类名

      // 开始拖拽时触发
      onStart: (evt) => {
        console.log("start:", JSON.stringify(tableData.value));
        dragState.isDragging = true;
        dragState.draggingIndex = evt.oldIndex;
        console.log('开始拖拽: 从索引', evt.oldIndex);
      },

      // 结束拖拽时触发
      onEnd: (evt) => {
        console.log("end:", JSON.stringify(tableData.value));
        dragState.isDragging = false;
        dragState.draggingIndex = -1;

        // 只有当位置发生变化时才更新数据
        if (evt.oldIndex !== evt.newIndex) {
          console.log(`拖拽结束: 从 ${evt.oldIndex} 到 ${evt.newIndex}`);

          // 复制原数组
          const newData = [...tableData.value];
          // 移除原位置的元素
          const [movedItem] = newData.splice(evt.oldIndex, 1);
          // 插入到新位置
          newData.splice(evt.newIndex, 0, movedItem);
          // 更新数据
          tableData.value = newData;

          // 这里可以添加保存到服务器的逻辑
          // saveNewOrder(tableData.value);
        }
      }
    });
  }
});

// 组件卸载时清理
onUnmounted(() => {
  if (dragState.instance) {
    dragState.instance.destroy();
  }
});

// 重置表格排序
const resetTable = () => {
  tableData.value = [...originalData];
};

// 暴露给模板的属性
const isDragging = ref(dragState.isDragging);
const draggingIndex = ref(dragState.draggingIndex);
</script>

<style scoped>
.draggable-table {
  max-width: 800px;
  margin: 2rem auto;
  padding: 1rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

h3 {
  text-align: center;
  color: #333;
  margin-bottom: 1.5rem;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
}

.data-table th,
.data-table td {
  padding: 0.8rem 1rem;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.data-table th {
  background-color: #f5f5f5;
  font-weight: 600;
  color: #555;
}

.data-table tr:hover {
  background-color: #fafafa;
}

.status-badge {
  padding: 0.2rem 0.6rem;
  border-radius: 4px;
  font-size: 0.8rem;
  color: white;
}

.status-badge.active {
  background-color: #4caf50;
}

.status-badge.inactive {
  background-color: #f44336;
}

.controls {
  margin-top: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reset-btn {
  padding: 0.5rem 1rem;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.reset-btn:hover {
  background-color: #0b7dda;
}

.debug-info {
  font-size: 0.9rem;
  color: #666;
}

/* 拖拽相关样式 */
.sortable-ghost {
  opacity: 0.5;
  background-color: #e0f7fa;
}

.sortable-chosen {
  background-color: #e3f2fd;
  border-left: 3px solid #2196f3;
}

.dragging {
  background-color: #e3f2fd;
}
</style>
